import { PlusOutlined, EditOutlined, DeleteOutlined, UploadOutlined, DownloadOutlined, EyeOutlined } from '@/utils/icons';
import React, { useState, useEffect } from 'react';
import { Card, Table, Button, Space, Modal, Form, Input, InputNumber, Select, DatePicker, message, Upload, Tag } from 'antd';

import { salaryApi } from '../../api/salaryApi';
import dayjs from 'dayjs';

const { Option } = Select;
const { RangePicker } = DatePicker;

export default function SalaryManagement() {
  const [loading, setLoading] = useState(false);
  const [salaryList, setSalaryList] = useState([]);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingRecord, setEditingRecord] = useState(null);
  const [form] = Form.useForm();

  useEffect(() => {
    fetchSalaryList();
  }, []);

  const fetchSalaryList = async () => {
    setLoading(true);
    try {
      const response = await salaryApi.getSalaryList();
      setSalaryList(response.data);
    } catch (error) {
      message.error('获取薪资列表失败');
    } finally {
      setLoading(false);
    }
  };

  const handleAdd = () => {
    setEditingRecord(null);
    form.resetFields();
    setModalVisible(true);
  };

  const handleEdit = (record) => {
    setEditingRecord(record);
    form.setFieldsValue({
      ...record,
      payDate: record.payDate ? dayjs(record.payDate) : null,
    });
    setModalVisible(true);
  };

  const handleDelete = async (id) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这条薪资记录吗？',
      onOk: async () => {
        try {
          await salaryApi.deleteSalary(id);
          message.success('删除成功');
          fetchSalaryList();
        } catch (error) {
          message.error('删除失败');
        }
      },
    });
  };

  const handleSubmit = async (values) => {
    try {
      const data = {
        ...values,
        payDate: values.payDate ? values.payDate.format('YYYY-MM-DD') : null,
      };

      if (editingRecord) {
        await salaryApi.updateSalary(editingRecord.id, data);
        message.success('更新成功');
      } else {
        await salaryApi.createSalary(data);
        message.success('创建成功');
      }
      
      setModalVisible(false);
      fetchSalaryList();
    } catch (error) {
      message.error(editingRecord ? '更新失败' : '创建失败');
    }
  };

  const handleImport = async (file) => {
    try {
      await salaryApi.importSalary(file);
      message.success('导入成功');
      fetchSalaryList();
    } catch (error) {
      message.error('导入失败');
    }
    return false;
  };

  const handleExport = async () => {
    try {
      const response = await salaryApi.exportSalary();
      const blob = new Blob([response], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = `薪资表_${dayjs().format('YYYY-MM-DD')}.xlsx`;
      link.click();
      window.URL.revokeObjectURL(url);
    } catch (error) {
      message.error('导出失败');
    }
  };

  const columns = [
    {
      title: '员工姓名',
      dataIndex: 'employeeName',
      key: 'employeeName',
    },
    {
      title: '部门',
      dataIndex: 'department',
      key: 'department',
    },
    {
      title: '基本工资',
      dataIndex: 'baseSalary',
      key: 'baseSalary',
      render: (value) => `¥${value.toLocaleString()}`,
    },
    {
      title: '绩效奖金',
      dataIndex: 'bonus',
      key: 'bonus',
      render: (value) => `¥${value.toLocaleString()}`,
    },
    {
      title: '实发工资',
      dataIndex: 'actualSalary',
      key: 'actualSalary',
      render: (value) => `¥${value.toLocaleString()}`,
    },
    {
      title: '发放日期',
      dataIndex: 'payDate',
      key: 'payDate',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => {
        const statusMap = {
          pending: { color: 'orange', text: '待发放' },
          paid: { color: 'green', text: '已发放' },
          cancelled: { color: 'red', text: '已取消' },
        };
        const config = statusMap[status] || { color: 'default', text: status };
        return <Tag color={config.color}>{config.text}</Tag>;
      },
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space>
          <Button type="link" icon={<EyeOutlined />} size="small">
            查看
          </Button>
          <Button type="link" icon={<EditOutlined />} size="small" onClick={() => handleEdit(record)}>
            编辑
          </Button>
          <Button type="link" icon={<DeleteOutlined />} size="small" danger onClick={() => handleDelete(record.id)}>
            删除
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div style={{ padding: 24 }}>
      <Card>
        <div style={{ marginBottom: 16 }}>
          <Space>
            <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
              新增薪资
            </Button>
            <Upload
              accept=".xlsx,.xls"
              beforeUpload={handleImport}
              showUploadList={false}
            >
              <Button icon={<UploadOutlined />}>
                导入薪资
              </Button>
            </Upload>
            <Button icon={<DownloadOutlined />} onClick={handleExport}>
              导出薪资
            </Button>
          </Space>
        </div>

        <Table
          columns={columns}
          dataSource={salaryList}
          loading={loading}
          rowKey="id"
          pagination={{
            total: salaryList.length,
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`,
          }}
        />
      </Card>

      <Modal
        title={editingRecord ? '编辑薪资' : '新增薪资'}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        onOk={() => form.submit()}
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
        >
          <Form.Item
            name="employeeName"
            label="员工姓名"
            rules={[{ required: true, message: '请输入员工姓名' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            name="department"
            label="部门"
            rules={[{ required: true, message: '请选择部门' }]}
          >
            <Select>
              <Option value="研发部">研发部</Option>
              <Option value="市场部">市场部</Option>
              <Option value="人事部">人事部</Option>
              <Option value="财务部">财务部</Option>
              <Option value="行政部">行政部</Option>
            </Select>
          </Form.Item>

          <Form.Item
            name="baseSalary"
            label="基本工资"
            rules={[{ required: true, message: '请输入基本工资' }]}
          >
            <InputNumber
              style={{ width: '100%' }}
              formatter={value => `¥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
              parser={value => value.replace(/¥\s?|(,*)/g, '')}
            />
          </Form.Item>

          <Form.Item
            name="bonus"
            label="绩效奖金"
          >
            <InputNumber
              style={{ width: '100%' }}
              formatter={value => `¥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
              parser={value => value.replace(/¥\s?|(,*)/g, '')}
            />
          </Form.Item>

          <Form.Item
            name="payDate"
            label="发放日期"
            rules={[{ required: true, message: '请选择发放日期' }]}
          >
            <DatePicker style={{ width: '100%' }} />
          </Form.Item>

          <Form.Item
            name="status"
            label="状态"
            rules={[{ required: true, message: '请选择状态' }]}
          >
            <Select>
              <Option value="pending">待发放</Option>
              <Option value="paid">已发放</Option>
              <Option value="cancelled">已取消</Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}
